<?php
namespace app\admin\controller;

use app\common\BaseAdminController;
use app\common\Result;
use app\common\Token;

class Auth extends BaseAdminController
{

    public function login()
    {
        // 获取用户名密码
        $data = $this->request->post();
        // 验证
        $validate = new \app\validate\Auth();
        if (! $validate->check($data)) {
            return Result::error($validate->getError());
        }
        // 验证验证码是否正确
        $authCode = \app\model\AuthCode::where('code', $data['code'])->find();
        if (! $authCode) {
            return Result::error("验证码错误");
        }
        // 验证验证码是否过期 10分钟
        if (strtotime($authCode->create_time) + 600 < time()) {
            return Result::error("验证码过期");
        }

        // 验证验证码是否正确
        if ($authCode->code != $data['code'] || $authCode->id != $data['id']) {
            return Result::error("验证码错误");
        }

        // 删除严重码
        $authCode->delete($authCode->id);

        // 验证用户名密码是否正确
        $admin = \app\model\Admin::where('username', $data['username'])->find();
        if (! $admin) {
            return Result::error("账号密码错误");
        }
        // 验证密码是否正确
        $result = password_verify($data['password'], $admin['password']);
        if (! $result) {
            return Result::error("账号密码错误");
        }
        // 登录成功，生成token
        $token = Token::createToken(['uid' => $admin['id']]);

        return Result::success($token, "登录成功");
    }

    public function codeImg($time)
    {
        // 生成4位随机验证码
        $code = strtoupper(substr(md5(uniqid()), 0, 4));

        // 创建验证码图片
        $width  = 100;
        $height = 30;
        $image  = imagecreatetruecolor($width, $height);

        // 设置背景色和文字颜色
        $bgColor   = imagecolorallocate($image, 255, 255, 255);
        $textColor = imagecolorallocate($image, 0, 0, 0);

        // 填充背景
        imagefilledrectangle($image, 0, 0, $width, $height, $bgColor);

        // 添加干扰线
        for ($i = 0; $i < 5; $i++) {
            $lineColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
            imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor);
        }

        // 写入验证码
        imagestring($image, 5, 30, 8, $code, $textColor);

        // 输出图片
        ob_start();
        imagepng($image);
        $imageData = ob_get_clean();
        imagedestroy($image);

        // 保存到数据库
        $authCode       = new \app\model\AuthCode();
        $authCode->code = $code;
        $authCode->id   = $time;
        $authCode->save();

        // 返回图片
        return response($imageData)->contentType('image/png');
    }
}
